package apptoko.com;

import java.io.IOException;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
import apptoko.com.adapter.ErrorHandler;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.event.Event;
import apptoko.com.event.Event.CallGoogleAPISuccessEvent;
import apptoko.com.event.Event.LoginFailEvent;
import apptoko.com.event.Event.RegisterFacebookSuccessEvent;
import apptoko.com.event.Event.RegisterGoogleSuccessEvent;
import apptoko.com.event.Event.RequestFailEvent;
import apptoko.com.event.Exception.AppJSONException;
import apptoko.com.event.Exception.GetGoogleTokenException;
import apptoko.com.event.Exception.GetGoogleTokenIOException;
import apptoko.com.event.Exception.GoogleApiIOException;
import apptoko.com.event.Exception.GoogleApiInterruptException;
import apptoko.com.event.Exception.GoogleLoginJSONException;
import apptoko.com.event.Exception.NetworkIOE;
import apptoko.com.model.AccessToken;
import apptoko.com.model.UserInfo;
import apptoko.com.network.ProgressDialogManager;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;
import apptoko.com.validator.Form;
import apptoko.com.validator.Validate;
import apptoko.com.validator.validate.ConfirmValidate;
import apptoko.com.validator.validator.EmailValidator;
import apptoko.com.validator.validator.MinimumUsernameValidator;
import apptoko.com.validator.validator.NotEmptyValidator;
import apptoko.com.validator.validator.UsernameSpecialCharacterValidator;
import apptoko.com.view.AlertDialogManager;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;
import com.appota.asdk.commons.AccessTokenUtil;
import apptoko.com.R;
import com.devspark.appmsg.AppMsg;
import com.easy.facebook.android.apicall.GraphApi;
import com.easy.facebook.android.data.User;
import com.easy.facebook.android.error.EasyFacebookError;
import com.easy.facebook.android.facebook.FBLoginManager;
import com.easy.facebook.android.facebook.Facebook;
import com.easy.facebook.android.facebook.LoginListener;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gms.auth.GoogleAuthUtil;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.util.AsyncExecutor;
import de.greenrobot.event.util.AsyncExecutor.RunnableEx;

public class RegisterActivity extends SherlockActivity implements OnClickListener, LoginListener {
	
	private String accessToken;
	private String fbEmail;
	private String fbToken;
	private String loginType;
	private String googleToken;
	private String googleEmail;
	private ProgressDialog pDialog;
	private BackgroundTasks bgTask;
	private EventBus eventBus;
	private AQuery aquery;
	private Form form;
	private Form usernameForm;
	private Form passwordForm;
	private Form confirmPasswordForm;
	private Form matchPasswordForm;
	private Form emailForm;
//	private Form formNoUserName;
	private EditText editUsername;
	private EditText editPassword;
	private EditText editConfirmPass;
	private EditText editEmail;
	private AccountManager mAccountManager;
	private FBLoginManager fbLoginManager;
	private String FB_APP_ID;
	private UserInfo user;
	private String email;
	///
	
		// Twitter
//	    private static Twitter twitter;
//	    private static RequestToken requestToken;
//		static String TWITTER_CONSUMER_KEY = "BQmiN1rkPWZC3cOT20YTw";
//	    static String TWITTER_CONSUMER_SECRET = "59Nz3WmW1daxD3v2uYAzYp2gdvvs4ZxMAP1CJa4s";
	 
//	    // Preference Constants
//	    static String PREFERENCE_NAME = "twitter_oauth";
//	    static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
//	    static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
//	    private static SharedPreferences mSharedPreferences;
//	    static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
//	    static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
//	    // Twitter oauth urls
//	    static final String URL_TWITTER_AUTH = "auth_url";
//	    static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
//	    static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setTheme(R.style.Theme_Styled_Home);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		
		EasyTracker.getInstance().setContext(this);
		bgTask = new BackgroundTasks(this);
		eventBus = EventBus.getDefault();
		aquery = new AQuery(this);
		form = new Form();
		usernameForm=new Form();
		passwordForm=new Form();
		confirmPasswordForm=new Form();
		emailForm=new Form();
		matchPasswordForm=new Form();
//		formNoUserName=new Form();
		getSupportActionBar().setTitle(R.string.register);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.action_bar_home);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
		loginType = getIntent().getStringExtra(Constants.LOGIN_TYPE);
		if(loginType.equalsIgnoreCase("facebook")){
			fbEmail = getIntent().getStringExtra(Constants.FB_EMAIL);
			fbToken = getIntent().getStringExtra(Constants.FB_TOKEN);
			aquery.id(R.id.edt_signup_email).text(fbEmail).enabled(false);
		} else if(loginType.equalsIgnoreCase("google")){
			googleEmail = getIntent().getStringExtra(Constants.GOOGLE_EMAIL);
			googleToken = getIntent().getStringExtra(Constants.GOOGLE_TOKEN);
			aquery.id(R.id.edt_signup_email).text(googleEmail).enabled(false);
		}
		
		editUsername = (EditText) findViewById(R.id.edt_signup_user);
		editPassword = (EditText) findViewById(R.id.edt_signup_pass);
		editConfirmPass = (EditText) findViewById(R.id.edt_signup_confirm_pass);
		editEmail = (EditText) findViewById(R.id.edt_signup_email);
		
		Validate userNameValidate = new Validate(editUsername);
		userNameValidate.addValidator(new NotEmptyValidator(this));
		userNameValidate.addValidator(new MinimumUsernameValidator(this));
		userNameValidate.addValidator(new UsernameSpecialCharacterValidator(this));
		Validate passValidate = new Validate(editPassword);
		passValidate.addValidator(new NotEmptyValidator(this));
		passValidate.addValidator(new MinimumUsernameValidator(this));
		Validate confirmValidate = new Validate(editConfirmPass);
		confirmValidate.addValidator(new NotEmptyValidator(this));
		confirmValidate.addValidator(new MinimumUsernameValidator(this));
		Validate emailValidate = new Validate(editEmail);
		EmailValidator mailVal1 = new EmailValidator(this);
	    emailValidate.addValidator(mailVal1);
		emailValidate.addValidator(new NotEmptyValidator(this));
		
		ConfirmValidate confirmFields = new ConfirmValidate(editPassword, editConfirmPass);
//		formNoUserName.addValidates(passValidate);
//		formNoUserName.addValidates(emailValidate);
//		formNoUserName.addValidates(confirmValidate);
//		formNoUserName.addValidates(confirmFields);
		form.addValidates(userNameValidate);
		form.addValidates(passValidate);
		form.addValidates(emailValidate);
		form.addValidates(confirmValidate);
		form.addValidates(confirmFields);
		
		usernameForm.addValidates(userNameValidate);
		passwordForm.addValidates(passValidate);
		emailForm.addValidates(emailValidate);
		confirmPasswordForm.addValidates(confirmFields);
		matchPasswordForm.addValidates(confirmValidate);
		aquery.id(R.id.btn_register).clicked(this);
		aquery.id(R.id.btn_login_gplus).clicked(this);
		aquery.id(R.id.btn_login_facebook).clicked(this);
//		aquery.id(R.id.btnLoginTwitter).clicked(this);
//		///!isTwitterLoggedInAlready()
//		if(true){
//			Uri uri = getIntent().getData();
//	        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
//	            // oAuth verifier
//	            String verifier = uri
//	                    .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
//	 
//	            try {
//	                // Get the access token
//	                new GetTwitterAsync(verifier).execute();
//	            } catch (Exception e) {
//	                // Check log for login errors
//	                Log.e("Twitter Login Error", "> " + e.getMessage());
//	            }
//	        }
//		}
//		
//		///
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getTracker().sendView("Register");
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		eventBus.register(this);
		com.facebook.AppEventsLogger.activateApp(this, getResources().getString(R.string.fb_app_id));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		eventBus.unregister(this);
	}
	
	private Account[] getAccounts() {
	    mAccountManager = AccountManager.get(this);
	    Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
	    return accounts;
	}
	
	private String[] getAccountNames(Account[] accounts){
	    String[] names = new String[accounts.length];
	    for (int i = 0; i < names.length; i++) {
	        names[i] = accounts[i].name;
	    }
	    return names;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_register:
			if(form.validate()){
				accessToken = Utils.getStaticAccessToken(this);
				if(loginType.equalsIgnoreCase("google")){
					pDialog = ProgressDialogManager.showProgressDialog(RegisterActivity.this, R.string.loading);
					bgTask.registerGoogle(accessToken, googleToken, editUsername.getText().toString(), editPassword.getText().toString(),email,getResources().getString(R.string.lang));
				} else if(loginType.equalsIgnoreCase("facebook")){
					pDialog = ProgressDialogManager.showProgressDialog(RegisterActivity.this, R.string.loading);
					bgTask.registerFacebook(accessToken, fbToken, editUsername.getText().toString(), editPassword.getText().toString(),email,getResources().getString(R.string.lang));
				} else {
					bgTask.register(accessToken, editUsername.getText().toString(), editPassword.getText().toString(), editEmail.getText().toString(),getResources().getString(R.string.lang));
				}
			}else{
				if(!usernameForm.validate()){
					editUsername.requestFocus();
				}else if(!passwordForm.validate()){
					editPassword.requestFocus();
				}else if(!confirmPasswordForm.validate()){
					editConfirmPass.requestFocus();
				}else if(!matchPasswordForm.validate()){
					editConfirmPass.requestFocus();
				}else{
					editEmail.requestFocus();
				}
			}
			break;
		case R.id.btn_login_gplus:
			AlertDialogManager am = new AlertDialogManager(this);
			final Account[] accs = getAccounts();
 			final String[] accounts = getAccountNames(accs);
			final String scopes = "oauth2:https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";
			am.showDialogWithItems(R.string.choose_google_account, accounts, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Bundle options = new Bundle();
					mAccountManager.getAuthToken(
						accs[which],                     // Account retrieved using getAccountsByType()
					    scopes,            // Auth scope
					    options,                        // Authenticator-specific options
					    RegisterActivity.this,                           // Your activity
					    new OnTokenAcquired(),          // Callback called when a token is successfully acquired
					    new Handler());    // Callback called if an error occurs
				}
			});
			break;
		case R.id.btn_login_facebook:
			konnectFacebook();
			break;
//		case R.id.btnLoginTwitter:
//			new GetTwitterAsync(null).execute();
//			break;
		}
	}
	
	private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
	    @Override
	    public void run(AccountManagerFuture<Bundle> result) {
	        Bundle bundle;
			try {
				Intent launch = (Intent) result.getResult().get(AccountManager.KEY_INTENT);
		        if (launch != null) {
		            startActivityForResult(launch, Constants.LOGIN_GOOGLE_REQUEST_CODE);
		            return;
		        }
				bundle = result.getResult();
				googleToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
				pDialog = ProgressDialogManager.showProgressDialog(RegisterActivity.this, R.string.loading);
				BackgroundTasks.callGoogleApi(googleToken);
			} catch (OperationCanceledException e) {
				e.printStackTrace();
			} catch (AuthenticatorException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
	}
	
	private void konnectFacebook(){
		String permissions[] = {"email", "read_stream","publish_stream", "read_friendlists"};
		FB_APP_ID = getResources().getString(R.string.fb_app_id);
		fbLoginManager = new FBLoginManager(this, R.layout.activity_login, FB_APP_ID, permissions);
		if(fbLoginManager.existsSavedFacebook()){
			fbLoginManager.loadFacebook();
		} else {
			fbLoginManager.login();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		if(requestCode == Constants.LOGIN_GOOGLE_REQUEST_CODE && resultCode == RESULT_OK){
			Bundle bundle = data.getExtras();
			googleToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
			pDialog = ProgressDialogManager.showProgressDialog(RegisterActivity.this, R.string.loading);
			BackgroundTasks.callGoogleApi(googleToken);
		}else if(resultCode == RESULT_OK){
			Log.e("ActivityResult","Result_Ok");
			if(data!=null){
				Log.e("ActivityResult","Result_Ok & data intent != null");
				if(fbLoginManager!=null){
					if(data.hasExtra("expires_in")&&data.hasExtra("access_token")){
						fbLoginManager.loginSuccess(data);
					}
				}else{
					Log.e("ActivityResult","Result_Ok & data intent != null & fbLoginManager = NULL");
				}
				
			}else{
				Log.e("ActivityResult","Result_Ok & data intent = NULL");
			}
		}else{
			Log.e("ActivityResult","Result_NOT_Ok");
		}
	}
	
	public void onEventMainThread(RegisterGoogleSuccessEvent event){
		AccessToken token = event.getAccessToken();
		SharedPreferences pref = getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE);
		//pref.edit().putString(Constants.ACCESS_TOKEN, token.getAccessToken()).commit();
		pref.edit().putBoolean(Constants.LOGIN, true).commit();
		((AppStoreVnApplication) getApplication()).setAccessToken(token.getAccessToken());
		((AppStoreVnApplication) getApplication()).setLogin(true);
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(token.getAccessToken());
		eventBus.post(new Event.LoginEvent(token.getAccessToken()));
		finish();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(RegisterFacebookSuccessEvent event){
		AccessToken token = event.getAccessToken();
		SharedPreferences pref = getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE);
		//pref.edit().putString(Constants.ACCESS_TOKEN, token.getAccessToken()).commit();
		pref.edit().putBoolean(Constants.LOGIN, true).commit();
		((AppStoreVnApplication) getApplication()).setAccessToken(token.getAccessToken());
		((AppStoreVnApplication) getApplication()).setLogin(true);
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(token.getAccessToken());
		eventBus.post(new Event.LoginEvent(token.getAccessToken()));
		finish();
		pDialog.dismiss();
	}//
	
	public void onEventMainThread(Event.NormalRegisterSuccessEvent event){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		AlertDialog.Builder builder=new Builder(RegisterActivity.this);
		editConfirmPass.setText("");
		editUsername.setText("");
		editEmail.setText("");
		editPassword.setText("");
		builder.setMessage(event.msg).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
			}
		});
		AlertDialog dialog=builder.create();
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.WHITE));
		dialog.setCancelable(false);
		dialog.show();
	}
	
	public void onEventMainThread(Event.RegisterSuccessEvent event){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		Log.e("RegisterSuccessEvent","RegisterSuccessEvent");
		AppMsg.makeText(this, R.string.register_success, AppMsg.STYLE_INFO, null).show();
		AlertDialog.Builder builder=new Builder(RegisterActivity.this);
		String msg=String.format(getResources().getString(R.string.register_success), editEmail.getText().toString());
		editConfirmPass.setText("");
		editUsername.setText("");
		editEmail.setText("");
		editPassword.setText("");
		builder.setMessage(msg).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				finish();
			}
		});
		AlertDialog dialog=builder.create();
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.WHITE));
		dialog.setCancelable(false);
		dialog.show();
	}
	
	public void onEventMainThread(Event.RegisterFailedEvent event){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		AppMsg.makeText(this, event.getErrorCode(), AppMsg.STYLE_ALERT, null).show();
	}
	
	public void onEventMainThread(NetworkIOE ioe){
		AppMsg.makeText(this, R.string.timeout, AppMsg.STYLE_ALERT, null).show();
	}
	
	public void onEventMainThread(AppJSONException ex){
		AppMsg.makeText(this, R.string.connect_error, AppMsg.STYLE_ALERT, null).show();
	}

	@Override
	public void loginSuccess(Facebook facebook) {
		// TODO Auto-generated method stub
		final String fbToken = facebook.getAccessToken();
		System.err.println(fbToken);
		final GraphApi graphApi = new GraphApi(facebook);
		pDialog = ProgressDialogManager.showProgressDialog(RegisterActivity.this, R.string.loading);
			AsyncExecutor.create().execute(new RunnableEx() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					User fbUser;
					try {
						fbUser = graphApi.getMyAccountInfo();
						email=fbUser.getEmail();
						accessToken = Utils.getStaticAccessToken(RegisterActivity.this);
						bgTask.loginFacebook(accessToken, fbToken, fbUser.getEmail(),getResources().getString(R.string.lang));
					} catch (EasyFacebookError e) {
						e.printStackTrace();
						AppMsg.makeText(RegisterActivity.this, e.getMessage(), AppMsg.STYLE_ALERT, null).show();
					}
				}
			});
	}
	
	@Override
	public void logoutSuccess() {
		// TODO Auto-generated method stub
		AppMsg.makeText(this, R.string.logout, AppMsg.STYLE_ALERT, null).show();
	}

	@Override
	public void loginFail() {
		// TODO Auto-generated method stub
		AppMsg.makeText(this, R.string.login_fb_fail, AppMsg.STYLE_ALERT, null).show();
	}
	
	public void onEventMainThread(CallGoogleAPISuccessEvent event){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		user = event.getUser();
		if(user!=null){
			accessToken = Utils.getStaticAccessToken(this);
			email=user.getEmail();
			bgTask.googleLogIn(accessToken, googleToken, user.getEmail(),getResources().getString(R.string.lang));
		}else{
			if(pDialog.isShowing())
			{
				pDialog.dismiss();
			}
			AppMsg.makeText(this, R.string.login_fail, AppMsg.STYLE_ALERT, null).show();
		}
		
	}
	
	public void onEventMainThread(GetGoogleTokenIOException ioe){
		Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(GetGoogleTokenException e){
		Toast.makeText(this, R.string.google_signin_request, Toast.LENGTH_SHORT).show();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(GoogleApiIOException ioe){
		Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(GoogleApiInterruptException ioe){
		Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(GoogleLoginJSONException je){
		Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
		pDialog.dismiss();
	}
	private boolean isgg = false;
	public void onEventMainThread(RequestFailEvent event){
		if(event.extra!=null){
			if(event.extra.equalsIgnoreCase("gg")){
				isgg=true;
			}else {
				isgg=false;
			}
		}
		if(event.getErrorCode() == 21){
			AlertDialogManager am = new AlertDialogManager(this);
			am.showButtonsDialog(R.string.google_first_login, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						Intent register = new Intent(RegisterActivity.this, RegisterActivity.class);
						if(isgg){
							register.putExtra(Constants.GOOGLE_EMAIL, user.getEmail());
							register.putExtra(Constants.GOOGLE_TOKEN, googleToken);
						}else{
							register.putExtra(Constants.FB_EMAIL, fbEmail);
							register.putExtra(Constants.FB_TOKEN, fbToken);
						}
						register.putExtra(Constants.LOGIN_TYPE, isgg?"google":"facebook");
						startActivity(register);
						finish();
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						((AppStoreVnApplication) getApplication()).setLogin(false);
						finish();
						break;
					}
				}
			});
		} else {
			ErrorHandler.getInstance().setContext(this).handleError(event.getErrorCode());
		}
		if(pDialog!=null && pDialog.isShowing())
		pDialog.dismiss();
	}
	
	public void onEventMainThread(Event.LoginGoogleSuccessEvent event){
		EasyTracker.getTracker().sendEvent(Constants.EVENT_ACTION, "Login", "LoginGoogleSuccess", Long.valueOf(1));
		AccessToken accessToken = event.getAccessToken();
		//PreferenceManager.getDefaultSharedPreferences(this).edit().putString(Constants.ACCESS_TOKEN, accessToken.getAccessToken()).commit();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putBoolean(Constants.LOGIN, true).commit();
		((AppStoreVnApplication) getApplication()).setAccessToken(accessToken.getAccessToken());
		((AppStoreVnApplication) getApplication()).setLogin(true);
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(accessToken.getAccessToken());
		AppMsg.makeText(this, R.string.login_success, AppMsg.STYLE_INFO, null).show();
		eventBus.post(new Event.LoginEvent(accessToken.getAccessToken()));
		Intent nofityIntent = new Intent("LOGGEDIN_AND_RELOAD");
		this.sendBroadcast(nofityIntent);
		finish();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(Event.LoginFacebookSuccessEvent event){
		EasyTracker.getTracker().sendEvent(Constants.EVENT_ACTION, "Login", "LoginFacebookSuccess", Long.valueOf(1));
		AccessToken accessToken = event.getAccessToken();
		//PreferenceManager.getDefaultSharedPreferences(this).edit().putString(Constants.ACCESS_TOKEN, accessToken.getAccessToken()).commit();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putBoolean(Constants.LOGIN, true).commit();
		((AppStoreVnApplication) getApplication()).setAccessToken(accessToken.getAccessToken());
		((AppStoreVnApplication) getApplication()).setLogin(true);
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(accessToken.getAccessToken());
		AppMsg.makeText(this, R.string.login_success, AppMsg.STYLE_INFO, null).show();
		eventBus.post(new Event.LoginEvent(accessToken.getAccessToken()));
		Intent nofityIntent = new Intent("LOGGEDIN_AND_RELOAD");
		this.sendBroadcast(nofityIntent);
		finish();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(Event.LoginSuccessEvent event){
		EasyTracker.getTracker().sendEvent(Constants.EVENT_ACTION, "Login", "LoginSuccess", Long.valueOf(1));
		((AppStoreVnApplication) getApplication()).setAccessToken(event.getAccessToken().getAccessToken());
		((AppStoreVnApplication) getApplication()).setLogin(true);
		SharedPreferences pref = getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE);
		//pref.edit().putString(Constants.ACCESS_TOKEN, event.getAccessToken().getAccessToken()).commit();
		pref.edit().putBoolean(Constants.LOGIN, true).commit();
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(event.getAccessToken().getAccessToken());
		eventBus.post(new Event.LoginEvent(event.getAccessToken().getAccessToken()));
		if(pDialog != null){
			pDialog.dismiss();
		}
		Intent nofityIntent = new Intent("LOGGEDIN_AND_RELOAD");
		this.sendBroadcast(nofityIntent);
		finish();
	}
	
	public void onEventMainThread(LoginFailEvent event){
		AppMsg.makeText(this, event.getErrorCode(), AppMsg.STYLE_ALERT, null).show();
		pDialog.dismiss();
	}
	
//	private class GetTwitterAsync extends AsyncTask<Void, Void, Void>{
//		private String verifier;
//		public GetTwitterAsync(String verifier){
//			this.verifier=verifier;
//		}
//		@Override
//		protected Void doInBackground(Void... params) {
//			loginToTwitter(verifier);
//			return null;
//		}
//		
//	}
//	private void loginToTwitter(String verifier) {
//        // Check if already logged in
//		if(verifier!=null){
//			try{
//			twitter4j.auth.AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
//            Editor e = mSharedPreferences.edit();
//            e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
//            e.putString(PREF_KEY_OAUTH_SECRET,
//                    accessToken.getTokenSecret());
//            e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
//            e.commit();
//			bgTask.loginTwitter(this.accessToken, requestToken.getToken(), requestToken.getTokenSecret());
//			}catch(Exception ex){}
//		}else{
//			ConfigurationBuilder builder = new ConfigurationBuilder();
//            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
//            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
//            Configuration configuration = builder.build();
//             
//            TwitterFactory factory = new TwitterFactory(configuration);
//            twitter = factory.getInstance();
// 
//            try {
//                requestToken = twitter
//                        .getOAuthRequestToken(TWITTER_CALLBACK_URL);
//                this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
//                        .parse(requestToken.getAuthenticationURL())));
//            } catch (TwitterException e) {
//                e.printStackTrace();
//            }
//		}
//    }
}
